//
//  MessageViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/3.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "MessageViewController.h"
#import "MsgCell.h"
#import "ChatViewController.h"
#import "BusinessService+User.h"
#import "GroupChatVC.h"
#import "SceneKPViewVC.h"
#import "KpListViewController.h"
#import "XhwStrangerVC.h"
@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationBarDelegate>
    @property (weak, nonatomic) IBOutlet UIView *gdView;
    @property (weak, nonatomic) IBOutlet UIView *gdBgView;
    @property (weak, nonatomic) IBOutlet UITableView *table;
    @property (nonatomic,strong) NSMutableArray * positionFor4ModeImage;
    @property (nonatomic,strong) NSMutableArray * positionFor9ModeImage;
    
    @end

@implementation MessageViewController
    {
        NSMutableArray *contentArr;
        
    }
- (void)viewDidLoad {
    _positionFor4ModeImage = [[NSMutableArray alloc]init];
    _positionFor9ModeImage = [[NSMutableArray alloc]init];
    [self initImageposition];
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]  addObserver:self  selector:@selector(initData:) name:@"getMessageList" object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self  selector:@selector(initData:) name:@"xhwgetMessageList" object:nil]; //xhw2018-2-11加
    
    
    [[NSNotificationCenter defaultCenter]  addObserver:self  selector:@selector(initData:) name:@"groupList" object:nil]; //xhw2018-1-25改bug15361
    _gdBgView.layer.cornerRadius = 5;
    _gdBgView.clipsToBounds = YES;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    _gdView.hidden = YES;
}


- (void)moreMiss {
    _gdView.hidden = YES;
}
    
-(void)scollTop:(NSNotification *)not{
    if (contentArr.count!=0) {
        [_table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}
-(void)initData:(NSNotification *)not{
    
    TCSession *ms;
    [contentArr removeAllObjects];  //xhw11月17号加
    contentArr = (NSMutableArray *)[TCSession getSessionListTimeLine];
//    for (int i = 0; i<contentArr.count; i++) {
//        TCSession *msg = [contentArr objectAtIndex:i];
//        if ([[UserDefaults readUserDefaultObjectValueForKey:@"ymzhiding"] intValue] == [msg.ID intValue]) {
//            ms = msg;
//            [contentArr removeObject:msg];
//        }
//    }
//    if (ms) {
//        [contentArr insertObject:ms atIndex:0];
//    }
    [self xhwHandleNotify];
    
    for (int i = 0; i<contentArr.count; i++) {
        TCSession *msg = [contentArr objectAtIndex:i];
        if ([UserDefaults readUserDefaultObjectValueForKey:@"ymzhiding"]) {
            NSString* isZhiDing = [UserDefaults readUserDefaultObjectValueForKey:@"ymzhiding"];
            if ([isZhiDing isEqualToString:msg.ID]){
                ms = msg;
                [contentArr removeObject:msg];
            }
        }
    }
    if (ms) {
        [contentArr insertObject:ms atIndex:0];
    }
    //xhw2018-1-22加
    contentArr = [self strangerSession:contentArr];

    [_table reloadData];
}
-(void)viewWillAppear:(BOOL)animated{
    //xhw2018-1-15:解决弹出的菜单不消失
    _gdView.hidden = YES;
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreMiss)];
    tapGes.cancelsTouchesInView = NO;
    tapGes.numberOfTapsRequired = 1;
    [_table addGestureRecognizer:tapGes];
    
    
    [self initData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scollTop:) name:@"scollTop" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearSession:) name:@"clearSessionGroup" object:nil];//xhw2018-1-26加
    
    [[AppDelegate shareDelegate]showMsgCount]; //xhw2018-2-23加
}

- (void)clearSession:(NSNotification*)sender {
    NSLog(@"xhw->MessageViewController->clearSession->进到通知了");

    [self initData];
    [_table reloadData];

}


//xhw2018-1-22加
- (NSMutableArray *) strangerSession:(NSMutableArray *)oldSession {
    NSMutableArray * strangerSessionList = [[NSMutableArray alloc] init];
//    TCSession * strangerSession = [[TCSession alloc] init];
    TCSession * strangerSession;
    if (oldSession.count > 0) {
        BOOL isStart = NO;
        for (int i = 0;i<oldSession.count;i++) {
            TCSession * session = oldSession[i];
            if (session.typeChat != forChatTypeGroup) {
                
                if ([session.name isEqualToString:@"熊4"]) {
                    NSLog(@"熊4消息->message->%@",strangerSession.message);
                    NSLog(@"熊4消息->messageType->%u",strangerSession.message.typeChat);
                    NSLog(@"熊4消息->messageContent->%@",strangerSession.message.contentFormat);
                }
                NSMutableArray *resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:session.ID typeChat:session.typeChat sinceRowID:0 maxRowID:0 count:0 page:0];
                if (resultArray.count != 0) {
                    TCMessage * xhwMessage = resultArray[resultArray.count - 1];
                    session.message = xhwMessage;
                    if ([[xhwMessage.to getExtendValueForKey:@"isfriend"] isEqualToString:@"0"]) {
                        if (isStart) {
                            [strangerSession setUnreadCount:(strangerSession.unreadCount + session.unreadCount)];
                            if (strangerSession.time < session.time) {
                                strangerSession.message = session.message;
                                strangerSession.time = session.time;
                            }
                        }
                        else {
                            isStart = YES;
                            strangerSession = session;
                        }
                    }
                    else {
                        [strangerSessionList addObject:session];
                    }
                }
                else {
                    [strangerSessionList addObject:session];
                }
            }
            else {
                [strangerSessionList addObject:session];
            }
            
        }
    }
    
    if (strangerSession) {
        NSLog(@"陌生人消息->会话id->%@",strangerSession.ID);
        NSLog(@"陌生人消息->会话content->%@",strangerSession.content);
        NSLog(@"陌生人消息->会话name->%@",strangerSession.name);
        NSLog(@"陌生人消息->会话type->%u",strangerSession.typeChat);
        NSLog(@"陌生人消息->messageType->%u",strangerSession.message.typeChat);
        NSLog(@"陌生人消息->messageContent->%@",strangerSession.message.contentFormat);
        strangerSession.name = @"陌生人消息";

        [strangerSessionList addObject:strangerSession];
    }
    return strangerSessionList;
}

- (TCSession *)xhwHandleNotifyToSession:(TCNotify *)notify typeName:(NSString *)typename {
    
    TCSession *xhwSession = [[TCSession alloc] init];
    xhwSession.time = notify.time;
    xhwSession.typeChat = notify.type;
    xhwSession.ID = notify.ID;
    if (notify.type == forNotifyType_tongyiwifi) {
        NSMutableArray *ary = [NSMutableArray array];
        [ary addObject:@"1012"];
        int unReadCount = [[ThinkChat instance ] getUnReadCountIncludeTypes:ary];
        NSLog(@"xhw->哈哈哈哈哈哈哈哈哈哈->同一wifi->%d",unReadCount);
        xhwSession.unreadCount = unReadCount;
        xhwSession.name = @"同一WIFI";
        
        NSMutableDictionary *dic = [JsonService jsonObjectWithString:notify.content];
        TCUser *u = notify.user;
        u.name = [dic objectForKey:@"username"];
        u.head = [dic objectForKey:@"headsmall"];
        xhwSession.user = u;
        xhwSession.content =[NSString stringWithFormat:@"%@发布了新的快拍！",[dic objectForKey:@"username"]];
        xhwSession.typeChat = 1012;
        
    }
    else if (notify.type == forNotifyType_fujingkuaipai) {
        NSMutableArray *ary = [NSMutableArray array];
        [ary addObject:@"1013"];
        
        int unReadCount = [[ThinkChat instance ] getUnReadCountIncludeTypes:ary];
        xhwSession.unreadCount = unReadCount;
        xhwSession.name = @"快拍照片";
        NSMutableDictionary *dic = [JsonService jsonObjectWithString:notify.content];
        TCUser *u = notify.user;
        u.name = [dic objectForKey:@"username"];
        u.head = [dic objectForKey:@"headsmall"];
        xhwSession.user = u;
        xhwSession.content =[NSString stringWithFormat:@"%@发布了新的快拍！",[dic objectForKey:@"username"]];
        xhwSession.typeChat = 1013;
        NSLog(@"xhwSession.id:%@",xhwSession.ID);
    }
    else if (notify.type == forNotifyType_wodekuaipai){
        
        NSLog(@"进入到我的快拍中了");
        NSMutableArray *ary = [NSMutableArray array];
        [ary addObject:@"1014"];
        
        int unReadCount = [[ThinkChat instance ] getUnReadCountIncludeTypes:ary];
        xhwSession.unreadCount = unReadCount;
        xhwSession.name = @"我的快拍";
        NSMutableDictionary *dic = [JsonService jsonObjectWithString:notify.content];
        TCUser *u = notify.user;
        u.name = [dic objectForKey:@"username"];
        u.head = [dic objectForKey:@"headsmall"];
        xhwSession.user = u;
        xhwSession.content = @"我发布了新的快拍";
        xhwSession.typeChat = 1014;
    }
    
    return xhwSession;
}
- (BOOL) isHasMessage:(NSString *)str {
    if (!contentArr || contentArr.count == 0) {
        return NO;
    }
    for (int i = 0; i<contentArr.count; i++) {
        TCSession * xhwSession = contentArr[i];
        if ([xhwSession.name isEqualToString:str]) {
            return YES;
        }
        else {
            continue;
        }
    }
    return NO;
}
#pragma mark -处理nitify
//将需要单独显示出来的通知类型重构一个session会话（三种：我的快拍，同一wifi,快拍照片）
- (void)xhwHandleNotify {
    NSMutableArray *notifyArr = (NSMutableArray*)[TCNotify getNotifyListTimeLineWithFinalNotify:nil];//获取所有的notify
        TCSession *lastestNotify = NULL;
    int j = 0;
        for (int i = 0; i<notifyArr.count; i++) {
            TCNotify *itemN = [notifyArr objectAtIndex:i];
            

              //211 209 300 、302、304 、1002、1003、1004、1006、1007、1008、1009、1011
            if (itemN) {
                if (itemN.type == 1002 || itemN.type == 1003 || itemN.type == 1004 || itemN.type == 1007 || itemN.type == 1008 || itemN.type == 1009 || itemN.type == 1006 || itemN.type == 211 || itemN.type == 209 || itemN.type == 300 || itemN.type == 302 || itemN.type == 304 || itemN.type == 1011) {
                    continue;
                }
                else {
                    j += 1;
                    NSMutableArray *logAry = [NSMutableArray array];
                    [logAry addObject:[NSString stringWithFormat:@"%u",itemN.type]];
                    int xhwunReadCount = [[ThinkChat instance ] getUnReadCountIncludeTypes:logAry];
                    
                    if (xhwunReadCount != 0) {
                        NSLog(@"item.type:%u",itemN.type);
                        NSLog(@"item未读数:%d",xhwunReadCount);
                    }
                    
                    if (itemN.type == forNotifyType_tongyiwifi) {
                        if (![self isHasMessage:@"同一WIFI"]) {
                            TCSession *xhwSession = [self xhwHandleNotifyToSession:itemN typeName:@"同一wifi"];
                            [contentArr addObject:xhwSession];
                        }

                    }
                    else if (itemN.type == forNotifyType_wodekuaipai) {
                        if (![self isHasMessage:@"我的快拍"]) {
                            TCSession *xhwSession = [self xhwHandleNotifyToSession:itemN typeName:@"我的快拍"];
                            [contentArr addObject:xhwSession];
                        }

                    }
                    else if (itemN.type == forNotifyType_fujingkuaipai) {
                        NSLog(@"xhw->messageVC->xhwHandleNotify->快拍照片->notify.id->%@",itemN.ID);
                        if (![self isHasMessage:@"快拍照片"]) {
                            TCSession *xhwSession = [self xhwHandleNotifyToSession:itemN typeName:@"快拍照片"];
                            [contentArr addObject:xhwSession];
                        }
                    }
                    else { //系统消息
                        NSMutableArray *ary = [NSMutableArray array];
                        [ary addObject:[NSString stringWithFormat:@"%u",itemN.type]];
                        NSLog(@"熊宏伟->msgVC->系统通知->单个通知的type->%u",itemN.type);

                        NSLog(@"熊宏伟->msgVC->系统通知->单个通知的content->%@",itemN.content);
                        int unReadCount = [[ThinkChat instance ] getUnReadCountIncludeTypes:ary];
                        NSLog(@"熊宏伟->msgVC->系统通知->单个通知的未读数>%d",unReadCount);
                        if (lastestNotify) {
                            if (lastestNotify.typeChat == itemN.type) {
                                lastestNotify.unreadCount = unReadCount;
                            }
                            else {
                                lastestNotify.unreadCount += unReadCount;
                            }
//                            lastestNotify.unreadCount += unReadCount;
                            if (itemN.time > lastestNotify.time) {
                                lastestNotify.content = itemN.content;
                            }
                            else {
                                
                            }
                        }
                        else {
                            lastestNotify = [[TCSession alloc] init];
                            lastestNotify.name = @"系统通知";
                            lastestNotify.user = itemN.user;
                            lastestNotify.time = itemN.time;
                            lastestNotify.content = itemN.content;
                            lastestNotify.unreadCount = unReadCount;
                            lastestNotify.typeChat = itemN.type;
                            lastestNotify.ID = itemN.ID;
                        }
                    }
                    if (lastestNotify.typeChat == 1001) { //有人评论了动态
                        lastestNotify.content = @"有人评论了你的动态";
                    }
                }
            }
        }
        if (lastestNotify) {
            [contentArr addObject:lastestNotify];
            if (lastestNotify.typeChat == 1015) { //新闻通知消息
                NSLog(@"新闻通知lastestNotify.content:%@",lastestNotify.content);
                NSDictionary * dic = [ValidateHelper jsonStringToDictionary:lastestNotify.content];
                lastestNotify.content = dic[@"url"];
            }
            
            if (lastestNotify.typeChat == 1017) { //点赞动态通知
                NSLog(@"有人赞了你的动态content:%@",lastestNotify.content);
                lastestNotify.content = @"有人赞了你的动态";
            }
            if (lastestNotify.typeChat == 1018) { //好友发动态通知
                NSLog(@"有好友发动态了content:%@",lastestNotify.content);
                lastestNotify.content = @"有好友发布了新的动态";
            }
        }
}

-(void)initData{
    TCSession *ms;
    [contentArr removeAllObjects];  //xhw11月17号加
    contentArr = (NSMutableArray *)[TCSession getSessionListTimeLine];

//    for (int i = 0; i<contentArr.count; i++) {
//        TCSession *msg = [contentArr objectAtIndex:i];
//        NSLog(@"xhw->MessageVC->viewWillAppear(initData)->contentArr%d->session.ID:%@",i,msg.ID);
//        if ([[UserDefaults readUserDefaultObjectValueForKey:@"ymzhiding"] intValue] == [msg.ID intValue]) {
//            ms = msg;
//            [contentArr removeObject:msg];
//        }
//    }
//    if (ms) {
//        [contentArr insertObject:ms atIndex:0];
//    }
    
    [self xhwHandleNotify];
    
    for (int i = 0; i<contentArr.count; i++) {
        TCSession *msg = [contentArr objectAtIndex:i];
        
        if ([UserDefaults readUserDefaultObjectValueForKey:@"ymzhiding"]) {
            NSString* isZhiDing = [UserDefaults readUserDefaultObjectValueForKey:@"ymzhiding"];

            if ([isZhiDing isEqualToString:msg.ID]) {
                ms = msg;
                NSLog(@"哈哈哈进入到删除数据源中的一个数据了");
                [contentArr removeObject:msg];
            }
        }
    }
    if (ms) {
        NSLog(@"又添加进去了");
        [contentArr insertObject:ms atIndex:0];
    }
    NSLog(@"%@",ms);
    contentArr = [self strangerSession:contentArr]; //xhw2018-1-22加
  
    [_table reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return contentArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    [[AppDelegate shareDelegate]showMsgCount];
    TCSession *msg = [contentArr objectAtIndex:indexPath.row];
    NSLog(@"cell中msg的类型:%u",msg.typeChat);
    MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MsgCell"];
    if([msg.name isEqualToString:@"系统通知"]){
        cell.img.image = [UIImage imageNamed:@"msgxt"];
        if (msg.typeChat == forNotifyType_HASATMEkuaipais) {//进入快拍
            cell.textContent.text = [NSString stringWithFormat:@"%@@了您",msg.user.ID];
        }
        if (msg.typeChat == forNotifyType_NEWMSGinKuaipais) {//进入快拍
            cell.textContent.text = [NSString stringWithFormat:@"%@评论了您",msg.user.ID];
        }
        cell.textContent.text = msg.content;
        
    }else if (msg.typeChat == forNotifyType_tongyiwifi){
        [cell.img sd_setImageWithURL:[NSURL URLWithString:msg.user.head] placeholderImage:[UIImage imageNamed:@"notimgs"]];
        cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
        cell.img.layer.masksToBounds = YES;
        cell.textContent.text = msg.content;
    }else if (msg.typeChat == forNotifyType_fujingkuaipai){
        
        [cell.img sd_setImageWithURL:[NSURL URLWithString:msg.user.head] placeholderImage:[UIImage imageNamed:@"notimgs"]];
        cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
        cell.img.layer.masksToBounds = YES;
        cell.textContent.text = msg.content;
    }else if (msg.typeChat == forNotifyType_wodekuaipai){
        [cell.img sd_setImageWithURL:[NSURL URLWithString:msg.user.head] placeholderImage:[UIImage imageNamed:@"notimgs"]];
        cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
        cell.img.layer.masksToBounds = YES;
        cell.textContent.text = msg.content;
    }
    
    else{
        if (msg.typeChat == 300) {
            NSMutableArray *heads = [[NSMutableArray alloc]init];
            NSArray *array = [msg.head componentsSeparatedByString:@","];
            for (NSString *img in array) {
                if (img.length == 0) {
                    continue;
                }
                UIImageView *ims = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
                ims.layer.cornerRadius = ims.frame.size.width/2;
                ims.clipsToBounds = YES;
                [ValidateHelper setimgeSize:img img:ims];
                [heads addObject:ims.image];
            }
            cell.img.backgroundColor = [UIColor clearColor];
            if (heads.count == 0) {
                [cell.img sd_setImageWithURL:[NSURL URLWithString:msg.head]
                            placeholderImage:[UIImage imageNamed:@"notimgs"]];
                
            }else{
                cell.img.image = [self makeGroupAvatar:heads];
            }
        }else{
            cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
            cell.img.clipsToBounds = YES;
            [cell.img sd_setImageWithURL:[NSURL URLWithString:msg.head]
                        placeholderImage:[UIImage imageNamed:@"notimgs"]];
        }
        if([msg.content rangeOfString:@"红包"].location !=NSNotFound){
            cell.textContent.text = @"[红包]";
        }else if([msg.content rangeOfString:@"LabVideo"].location !=NSNotFound){
            cell.textContent.text = @"[视频]";
        }
        else if([msg.content rangeOfString:@"转赠"].location !=NSNotFound){
            cell.textContent.text = @"[转赠]";
        }
        else if([msg.content rangeOfString:@"共享"].location !=NSNotFound){
            cell.textContent.text = @"[位置共享]";
        }
        else if([msg.content rangeOfString:@"LabLocation"].location !=NSNotFound){
            cell.textContent.text = @"[位置]";
        }
        else if([msg.content rangeOfString:@"LabAudio"].location !=NSNotFound){
            cell.textContent.text = @"[声音]";
        }
        else if([msg.content rangeOfString:@"LabImage"].location !=NSNotFound){
            cell.textContent.text = @"[图片]";
        }else{
            [ValidateHelper ReplaceExpression:msg.content label:cell.textContent size:14 isr:NO];
        }
    }
    
    NSString *isFriend = [msg getExtendValueForKey:@"isfriend"];
    if (isFriend) {
        if ([isFriend isEqualToString:@"1"]) {
            cell.name.text = @"陌生人消息";
        }
        else {
            cell.name.text = msg.name;
        }
    }
    else {
        cell.name.text = msg.name;
    }
        
    //xhw2018-1-19改15268
//    cell.name.text = msg.name;
    
    NSString *time = [ValidateHelper timeStringWith:msg.time multiLine:NO];
    NSString *distance = [msg getExtendValueForKey:@"distance"];
    if (distance) {
        
    }
    else {
        distance = 0;
    }
    if (msg.unreadCount!=0) {
        [cell.unreadCount setTitle:[NSString stringWithFormat:@"%d",msg.unreadCount] forState:UIControlStateNormal];
        cell.unreadCount.hidden = NO;
    }else{
        cell.unreadCount.hidden = YES;
    }
//    cell.time.text = time;
    //xhw2018-1-19改bug15265
    cell.time.text = [NSString stringWithFormat:@"%@|%@",[ValidateHelper DistanceFormat:distance],time];
    return  cell;
}
    
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TCSession *msg = [contentArr objectAtIndex:indexPath.row];
    NSLog(@"xhw->messageVC->didSelectRow->msg.ID:%@",msg.ID);
    if (msg.typeChat==200 || msg.typeChat == 300) {//群聊
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        GroupChatVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupChatVC"];
        searchResultDetailController.tcs = msg;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    }else if (msg.typeChat == forNotifyType_tongyiwifi){//同一WIFI
        NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
        for (TCNotify *item in arr) {
            if (item.type == forNotifyType_tongyiwifi) {
                [[ThinkChat instance] hasReadNotify:item];
            }
        }
        [[AppDelegate shareDelegate] showMsgCount];
        //xhw11月9号改:
//        KpListViewController *vc = [KpListViewController new];
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        KpListViewController *vc = (KpListViewController*)([customerStoryboard instantiateViewControllerWithIdentifier:@"KpListViewController"]);
        vc.title = @"同一wifi";
        vc.kptype = 2;
        vc.nav = self.navigationController;
        
        [self.navigationController pushViewController:vc animated:YES];
    }else if (msg.typeChat == forNotifyType_fujingkuaipai){//快拍照片
        
        NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
        for (TCNotify *item in arr) {
            if (item.type == forNotifyType_fujingkuaipai) {
                [[ThinkChat instance] hasReadNotify:item];
            }
        }
        [[AppDelegate shareDelegate] showMsgCount];
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        KpListViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"KpListViewController"];
        searchResultDetailController.title = @"快拍照片";
        searchResultDetailController.kptype = 7;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
    }else if (msg.typeChat == forNotifyType_wodekuaipai){
        NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
        for (TCNotify *item in arr) {
            if (item.type == forNotifyType_wodekuaipai) {
                [[ThinkChat instance] hasReadNotify:item];
            }
        }
        [[AppDelegate shareDelegate] showMsgCount];
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        KpListViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"KpListViewController"];
        searchResultDetailController.title = @"我的快拍";
        searchResultDetailController.kptype = 6;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
        
    }else if([msg.name isEqualToString:@"系统通知"]){
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"NotifyListController"];
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
        
    }
    //xhw2018-1-22加:
    else if ([msg.name isEqualToString:@"陌生人消息"]) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"strangerVC"];
        searchResultDetailController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    }
    else{
        
        MsgCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        ChatViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"ChatVC"];
        searchResultDetailController.image = cell.img.image;
        searchResultDetailController.tcs = msg;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
    }
    NSMutableArray *ary = [NSMutableArray array];
    [ary addObject:@"1002"];
    [ary addObject:@"1003"];
    [ary addObject:@"1004"];
    [ary addObject:@"1007"];
    [ary addObject:@"1008"];
    [ary addObject:@"1009"];
    [ary addObject:@"1006"];
    [ary addObject:@"1013"];
    [ary addObject:@"1014"];
    
    int unReadCount = [[ThinkChat instance] getUnReadCountWithType:ary];
//    NSLog(@"未读数%d",unReadCount);
    unReadCount = [TCMessage getUnreadCountWithTypeChat:forChatTypeUser];
//    NSLog(@"未读数%d",unReadCount);
    unReadCount = [TCMessage getUnreadCountWithTypeChat:forChatTypeRoom];
//    NSLog(@"未读数%d",unReadCount);

}
    
-(BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item{
    [self.navigationController popViewControllerAnimated:YES];
    return YES;
}
    
#pragma mark 设置可以进行编辑
    
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    
    {
        return YES;
    }
#pragma mark 设置编辑的样式
    
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    
    {
        
        return UITableViewCellEditingStyleDelete;
        
    }
#pragma mark 设置可以移动
    
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

    {

        return YES;

    }
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
    
    {
        
        // 添加一个删除按钮
        
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            NSLog(@"点击了删除");
            
            TCSession * item = [contentArr objectAtIndex:indexPath.row];
            if (item.typeChat == forNotifyType_wodekuaipai || item.typeChat == forNotifyType_fujingkuaipai || item.typeChat == forNotifyType_tongyiwifi) {
                NSMutableArray *notifyArr = (NSMutableArray*)[TCNotify getNotifyListTimeLineWithFinalNotify:nil];
                for (int i = 0; i<notifyArr.count; i++) {
                    TCNotify *notify = notifyArr[i];
                    if (notify.type == item.typeChat) {
                        [TCNotify hasDeleteNotify:notify];
                    }
                }
            }
            //xhw2018-1-26加 if else才能把单独拿出来的notify清楚掉
            else {
                if ([item.name isEqualToString:@"系统通知"]) {
                     NSMutableArray *notifyArr = (NSMutableArray*)[TCNotify getNotifyListTimeLineWithFinalNotify:nil];
                    for (int i = 0; i<notifyArr.count; i++) {
                        TCNotify *notify = notifyArr[i];
                        switch (notify.type) {
                            case forNotifyType_fujingkuaipai:
                                break;
                            case forNotifyType_tongyiwifi:
                                break;
                            case forNotifyType_wodekuaipai:
                                break;
                            default:
                                [TCNotify hasDeleteNotify:notify];
                                break;
                        }
                    }
                }
                else if ([item.name isEqualToString:@"陌生人消息"]) {
                    NSMutableArray *xhwcontentArr = (NSMutableArray *)[TCSession getSessionListTimeLine];
                    for (int i = 0; i<xhwcontentArr.count; i++) {
                        TCSession *session = [xhwcontentArr objectAtIndex:i];
                        
                        NSMutableArray *resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:session.ID typeChat:session.typeChat sinceRowID:0 maxRowID:0 count:0 page:0];
                        if (resultArray.count != 0) {
                            TCMessage * xhwMessage = resultArray[resultArray.count - 1];

                            session.message = xhwMessage;
                            if ([[xhwMessage.to getExtendValueForKey:@"isfriend"] isEqualToString:@"0"]) {
                                [[AppDelegate shareDelegate] clearSessionID:session.ID typeChat:session.typeChat];
                            }
                        }
                    }
                }
                else {
                    [[AppDelegate shareDelegate] clearSessionID:item.ID typeChat:item.typeChat];
                }
                
            }
//            [[AppDelegate shareDelegate] clearSessionID:item.ID typeChat:item.typeChat];
            [self initData];
            [_table reloadData];
            [[AppDelegate shareDelegate]showMsgCount]; //xhw2018-1-26加
            // 1. 更新数据
            
            //        [_allDataArray removeObjectAtIndex:indexPath.row];
            
            // 2. 更新UI
            
            //        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            
        }];
        
        
        
        // 删除一个置顶按钮
        
        UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            NSLog(@"点击了置顶");
            
            TCSession * item = [contentArr objectAtIndex:indexPath.row];
            [UserDefaults writeUserDefaultObjectValue:item.ID withKey:@"ymzhiding"];
            
            [self initData];
            [_table reloadData];
            
            // 1. 更新数据
            
            [contentArr exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
            
            
            
            // 2. 更新UI
            
            NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
            
            [tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
            
        }];
        
        topRowAction.backgroundColor = UIColorFromRGB(0x996633);
        
        
        
        // 添加一个更多按钮
        
        UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"忽略未读" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            NSLog(@"点击了更多");
            
            
            
            TCSession * item = [contentArr objectAtIndex:indexPath.row];
            
            if([item.name isEqualToString:@"系统通知"]){
                NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
                for (TCNotify *notify in arr) { //xhw2018-1-26改item->notify
                    if (notify.type == forNotifyType_tongyiwifi || notify.type  == forNotifyType_fujingkuaipai || notify.type == forNotifyType_wodekuaipai) {
                        
                    }
                    else {
                        [[ThinkChat instance]hasReadNotify:notify];
                    }
//                    [[ThinkChat instance]hasReadNotify:notify]; //xhw2018-1-26改item->notify
                }
                [[AppDelegate shareDelegate]showMsgCount];
            }
            else if ([item.name isEqualToString:@"陌生人消息"]) {
                NSMutableArray *xhwcontentArr = (NSMutableArray *)[TCSession getSessionListTimeLine];
                for (int i = 0; i<xhwcontentArr.count; i++) {
                    TCSession *session = [xhwcontentArr objectAtIndex:i];
                    
                    NSMutableArray *resultArray = (NSMutableArray *)[[ThinkChat instance] getMessageListTimeLineWithID:session.ID typeChat:session.typeChat sinceRowID:0 maxRowID:0 count:0 page:0];
                    if (resultArray.count != 0) {
                        TCMessage * xhwMessage = resultArray[resultArray.count - 1];
                        
                        session.message = xhwMessage;
                        if ([[xhwMessage.to getExtendValueForKey:@"isfriend"] isEqualToString:@"0"]) {
                            [[ThinkChat instance] hasReadSessionID:session.ID typeChat:session.typeChat];
                        }
                    }
                }
            }
            if (item.typeChat == forNotifyType_wodekuaipai) {
                NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
                for (TCNotify *notify in arr) {
                    if (notify.type == forNotifyType_wodekuaipai) {
                        [[ThinkChat instance] hasReadNotify:notify];
                    }
                }
            }
            else if (item.typeChat == forNotifyType_tongyiwifi){
                NSLog(@"同一wifi");
                NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
                for (TCNotify *notify in arr) {
                    if (notify.type == forNotifyType_tongyiwifi) {
                        NSLog(@"是进到了标记同一wifi为已读");
                        [[ThinkChat instance] hasReadNotify:notify];
                    }
                }
            }else if (item.typeChat == forNotifyType_fujingkuaipai){
                NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
                for (TCNotify *notify in arr) {
                    if (notify.type == forNotifyType_fujingkuaipai) {
                        [[ThinkChat instance] hasReadNotify:notify];
                    }
                }
            
            }
//            else if(item.typeChat == forNotifyType_fujingkuaipai){//附近快拍
//
//                NSArray* arr = [[ThinkChat instance] getNotifyListTimeLineWithFinalNotify:nil];
//                for (TCNotify *item in arr) {
//                    [[ThinkChat instance]hasReadNotify:item];
//                }
//                [[AppDelegate shareDelegate]showMsgCount];
//
//            }

            
            else{
                
                [[ThinkChat instance]hasReadSessionID:item.ID typeChat:item.typeChat];
                
            }
            [self initData];
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
            
        }];
        
        moreRowAction.backgroundColor = [UIColor lightGrayColor];
        
        
        // 将设置好的按钮放到数组中返回
        
        // return @[deleteRowAction, topRowAction, moreRowAction];
        
        return @[deleteRowAction,moreRowAction,topRowAction];
        
    }
    

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        _gdView.hidden = YES;
        
    }
#pragma mark 更多
- (IBAction)gdAction:(UIButton *)sender {
    //    _gdBgView.layer.opacity = 0.5;
    _gdView.hidden = NO;
    
    
}
#pragma  mark 发起会话
- (IBAction)faqihuihuaAction:(UIButton *)sender {
    
    _gdView.hidden = YES; //xhw2018-1-10加
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"NewConversationVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
#pragma mark 添加好友
- (IBAction)addAction:(id)sender {
    _gdView.hidden = YES; //xhw2018-1-10加
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddFriendsVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
#pragma mark 扫一扫
- (IBAction)sysAction:(UIButton *)sender {
    _gdView.hidden = YES; //xhw2018-1-10加
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"QRCodeVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
    
- (IBAction)hulvewAction:(id)sender {
    _gdView.hidden = YES;
//    NSLog(@"%@",[[ThinkChat instance]getLatestNotify]);
    NSArray<TCSession *> *sec = contentArr;
    for (TCSession * session in sec) {
        [[ThinkChat instance] hasReadSessionID:session.ID typeChat:forChatTypeUser];
        [[ThinkChat instance] hasReadSessionID:session.ID typeChat:forChatTypeRoom];
        [[ThinkChat instance] hasReadSessionID:session.ID typeChat:forChatTypeGroup];
        
    }
//    NSMutableArray *ary = [NSMutableArray array];
//    //xhw2018-1-8改:bug14938(把所有的消息类型都标识为已读)
//    [ary addObject:@"1012"];
//    [ary addObject:@"1013"];
//    [ary addObject:@"1014"];
//    [ary addObject:@"1015"];
//    [ary addObject:@"1001"];
//
//
//    [ary addObject:@"1002"];
//    [ary addObject:@"1003"];
//    [ary addObject:@"1004"];
//    [ary addObject:@"1007"];
//    [ary addObject:@"1008"];
//    [ary addObject:@"1009"];
//    [ary addObject:@"1006"];
//    NSArray<TCNotify *> *notyArr = [TCNotify getNotifyListTimeLineForTypes:ary];
    NSArray<TCNotify *> *notyArr = [TCNotify getNotifyListTimeLineWithFinalNotify:nil];
    
    for (TCNotify *not in notyArr) {
        [TCNotify hasReadNotify:not];
    }
    TCNotify* itemN = [TCNotify getLatestNotify];
    
    [self initData:nil];
    [self.table reloadData];
    //    [ThinkChat instance]hasReadSessionID: typeChat:
}
    
    
- (UIImage *)makeGroupAvatar: (NSMutableArray *)imageArray {
    //数组为空，退出函数
    if ([imageArray count] == 0){
        return nil;
    }
    
    UIView *groupAvatarView = [[UIView alloc]initWithFrame:CGRectMake(0,0,193,193)];
    groupAvatarView.backgroundColor = UIColorFromRGB(0xEFEFF4);
    
    for (int i = 0; i < [imageArray count]; i++){
        UIImageView *tempImageView;
        if ([imageArray count] < 5){
            tempImageView = [[UIImageView alloc]initWithFrame:[[_positionFor4ModeImage objectAtIndex:i]CGRectValue]];
        }
        else{
            tempImageView = [[UIImageView alloc]initWithFrame:[[_positionFor9ModeImage objectAtIndex:i]CGRectValue]];
        }
        UIImage *imgss = [imageArray objectAtIndex:i];
        imgss = [UIImage createRoundedRectImage:imgss size:imgss.size radius:imgss.size.width/2];
        [tempImageView setImage:[UIImage borderImg:imgss]];
        [groupAvatarView addSubview:tempImageView];
    }
    
    //把UIView设置为image并修改图片大小55*55
    UIImage *reImage = [self scaleToSize:[self convertViewToImage:groupAvatarView]size:CGSizeMake(80, 80)];
    
    return reImage;
}
-(UIImage*)convertViewToImage:(UIView*)v{
    
    CGSize s = v.bounds.size;
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数。
    
    UIGraphicsBeginImageContextWithOptions(s, YES, [UIScreen mainScreen].scale);
    
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}
    
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}
    
- (void)initImageposition{
    
    //初始化4图片模式和9图片模式
    for(int i = 0; i < 9; i++){
        CGRect tempMode4Rect;
        CGRect tempMode9Rect;
        float mode4PositionX = 0;
        float mode4PositionY = 0;
        float mode9PositionX = 0;
        float mode9PositionY = 0;
        
        switch (i) {
            case 0:
            mode4PositionX = 4;
            mode4PositionY = 4;
            mode9PositionX = 4;
            mode9PositionY = 4;
            break;
            case 1:
            mode4PositionX = 98.5;
            mode4PositionY = 4;
            mode9PositionX = 67;
            mode9PositionY = 4;
            break;
            case 2:
            mode4PositionX = 4;
            mode4PositionY = 98.5;
            mode9PositionX = 130;
            mode9PositionY = 4;
            break;
            case 3:
            mode4PositionX = 98.5;
            mode4PositionY = 98.5;
            mode9PositionX = 4;
            mode9PositionY = 67;
            break;
            case 4:
            mode9PositionX = 67;
            mode9PositionY = 67;
            break;
            case 5:
            mode9PositionX = 130;
            mode9PositionY = 67;
            break;
            case 6:
            mode9PositionX = 4;
            mode9PositionY = 130;
            break;
            case 7:
            mode9PositionX = 67;
            mode9PositionY = 130;
            break;
            case 8:
            mode9PositionX = 130;
            mode9PositionY = 130;
            break;
            default:
            break;
        }
        
        //添加4模式图片坐标到数组
        if (i < 4 ){
            tempMode4Rect = CGRectMake(mode4PositionX+5, mode4PositionY+5, 90.5, 90.5);
            [_positionFor4ModeImage addObject:[NSValue valueWithCGRect:tempMode4Rect]];
        }
        
        //添加4模式图片坐标到数组
        tempMode9Rect = CGRectMake(mode9PositionX+5, mode9PositionY+5, 59, 59);
        [_positionFor9ModeImage addObject:[NSValue valueWithCGRect:tempMode9Rect]];
    }
}
@end
